package cn.studyjams.s1.contest.autohello;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import cn.studyjams.s1.contest.autohello.model.User;

public class IndexActivity extends BaseActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        SignInFragment.SignInListener,
        SignUpFragment.SignUpListener {

    private static final String TAG = "IndexActivity";
    private static final String USER_G = "google";
    private static final String USER_F = "facebook";
    private static final String USER_E = "email";

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference mDatabaseReference;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        // Initialize FirebaseAuth
        mAuth = FirebaseAuth.getInstance();
        mDatabaseReference = FirebaseDatabase.getInstance().getReference();
        mAuthListener = new FirebaseAuth.AuthStateListener() {

            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                    startActivity(new Intent(IndexActivity.this, MainActivity.class));
                    finish();
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };

        final ImageView logo = (ImageView) findViewById(R.id.logo);

        AnimationDrawable animation = new AnimationDrawable();
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_tomato), 1000);
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_banana), 1000);
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_cucumber), 1000);
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_default), 1000);
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_blueberry), 1000);
        animation.addFrame(ContextCompat.getDrawable(this, R.mipmap.autohello_grape), 1000);

        animation.setOneShot(false);
        logo.setImageDrawable(animation);

        animation.start();

        mFragmentManager = getSupportFragmentManager();
        Fragment fragment = new SignInFragment();

        mFragmentManager.beginTransaction().
                replace(R.id.fragment_container, fragment)
                .commit();
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
        setResult(RESULT_CANCELED, new Intent());
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSignIn(String email, String password) {
        Log.d(TAG, "sign in:" + email + " " + password);

        showProgressDialog(getString(R.string.loading));
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());

                        hideProgressDialog();
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithEmail:failed", task.getException());
                            Toast.makeText(IndexActivity.this, R.string.auth_failed,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onSignUpButton() {
        Log.d(TAG, "sign up");
        Fragment fragment = new SignUpFragment();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

        fragmentTransaction
                .setCustomAnimations(
                        R.anim.fragment_slide_right_enter,
                        R.anim.fragment_slide_left_exit
                ).replace(R.id.fragment_container, fragment).commit();
    }

    @Override
    public void onSignUp(String email, String password) {
        Log.d(TAG, "sign up:" + email + " " + password);

        showProgressDialog(getString(R.string.loading));
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {
                        FirebaseUser user = authResult.getUser();
                        if (user != null) {
                            writeNewUser(
                                    mDatabaseReference,
                                    user.getUid(),
                                    user.getDisplayName(),
                                    user.getEmail(),
                                    user.getPhotoUrl(),
                                    USER_E
                            );
                        }
                    }
                })
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
                        hideProgressDialog();

                        if (!task.isSuccessful()) {
                            Toast.makeText(IndexActivity.this, R.string.auth_failed,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onSignInButton() {
        Log.d(TAG, "sign in");
        Fragment fragment = new SignInFragment();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(
                R.anim.fragment_slide_left_enter,
                R.anim.fragment_slide_right_exit
        ).replace(R.id.fragment_container, fragment).commit();
    }

    public void writeNewUser(DatabaseReference databaseRef, String userId, String name, String email, Uri photo, String type) {

        String photoUrl = photo == null ? "" : photo.toString();
        String username = name == null ? usernameFromEmail(email) : name;

        User user = new User(userId, username, "", email, photoUrl, type);

        databaseRef.child("users").child(userId).setValue(user);
    }

    public String usernameFromEmail(String email) {
        if (email.contains("@")) {
            return email.split("@")[0];
        } else {
            return email;
        }
    }
}
